package net.chenlin.dp.modules.business.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.chenlin.dp.common.entity.R;
import net.chenlin.dp.common.utils.UploadUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Yangsm
 * @ClassName: FileUploadController
 * @Description: TODO
 * @date 2023年05月14日 17:25
 */
@Slf4j
//@RestController
//@RequestMapping("/file")
//@Api(tags = "文件上传下载")
public class FileUploadController {

//    @PostMapping("/upload")
//    public String upload(MultipartFile uploadFile, HttpServletRequest req){
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        //String realPath = "/home/dianbiao/data/ ";
//        String realPath = "D://upload";
//        String format = sdf.format(new Date());
//        File folder = new File(format+realPath);
//        if(!folder.isDirectory()){
//            folder.mkdirs();
//        }
//        String oldName = uploadFile.getOriginalFilename();
//        Long sixe = uploadFile.getSize();
//        //String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
//        try{
//            uploadFile.transferTo(new File(folder,oldName));
//            String filePath = req.getScheme()+"/"+req.getServerName()+":"+req.getServerPort()+"/uploadFile"+format + oldName ;
//            return filePath ;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "上传失败" ;
//    }

//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    @ApiOperation(value = "上传单个文件")
//    public R upload(@RequestPart MultipartFile file) throws IOException {
//        String fileName = file.getOriginalFilename();
//        String filePath = "D://upload" + fileName;
//        File dest = new File(filePath);
//        if(dest.exists()){
//            return R.error("该文件名的文件已存在，请重新上传！");
//        }
//        Files.copy(file.getInputStream(), dest.toPath());
//        return R.ok("Upload file success : " + dest.getAbsolutePath());
//    }

    /**
     * 1.文件保存在服务器，url地址保存在数据库
     * 上传成功之后返回成功保存的url地址
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {
            String uploadPath = "D://upload";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() + suffixName;
            File localFile = new File(uploadPath + "\\" +filename);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                return filename;//上传成功，返回保存的文件地址
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return "";
            }
        } else {
            System.out.println("文件为空");
            return "";
        }
    }

    @PostMapping("/multiUpload")
    public String multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "D://";
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "上传第" + (i++) + "个文件失败";
            }
            String fileName = file.getOriginalFilename();

            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                log.info("第" + (i + 1) + "个文件上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "上传第" + (i++) + "个文件失败";
            }
        }
        return "上传成功";
    }
}
